package smecta.client.print.util;

import java.io.*;
import java.nio.charset.Charset;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;

import javafx.beans.property.SimpleStringProperty;
import javafx.beans.value.ObservableValue;
import javafx.collections.ObservableList;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.control.TableColumn.CellDataFeatures;
import javafx.scene.control.TableColumn.CellEditEvent;
import javafx.scene.control.cell.CheckBoxTableCell;
import javafx.scene.control.cell.TextFieldTableCell;
import javafx.util.Callback;
import javafx.util.converter.DefaultStringConverter;

public class TableUtil {
	static String filePath = "dependencies/db/TitleSet.ini";
	static List<String> columnsNames = null;
	static List<String> columnsIds = null;


    public static LinkedHashMap<String, Object[]> getTableColumnsConfig() {
        LinkedHashMap<String, Object[]> columnsConfig = new LinkedHashMap<String, Object[]>();
        try (BufferedReader reader = new BufferedReader(new FileReader(filePath, Charset.forName("UTF-8")))) {
            String line;
            String title = null;
            int width = 0;
            boolean isColumnSection = false;
            String id = "";
            String preLine = "";
            while ((line = reader.readLine()) != null) {
                line = line.trim();
                if (line.startsWith("[") && line.endsWith("]")) {
                    if (isColumnSection && !id.isEmpty()) {
                        System.out.println("id:" + id);
                        columnsConfig.put(id, new Object[]{title, width});
                    }
                    // Reset for the new section
                    title = null;
                    width = 0;
                    id = "";
                    isColumnSection = line.contains("Title");
                } else if (isColumnSection) {
                    if (line.startsWith("title=")) {
                        title = line.substring("title=".length()).trim();
                    } else if (line.startsWith("width=")) {
                        width = Integer.parseInt(line.substring("width=".length()).trim());
                    }
                }
                if (isColumnSection && line.startsWith("[") && line.endsWith("]")) {
                    id = line.replace("[", "").replace("]", "");
                }
                preLine = line;
            }
            // Add the last column if exists
            if (isColumnSection && title != null && !id.isEmpty()) {
                System.out.println("id:" + id);
                columnsConfig.put(id, new Object[]{title, width});
            }

        } catch (IOException e) {
            e.printStackTrace();
        }
        return columnsConfig;
    }

    public static void saveTableColumnsConfig(TableView<RowData> dataTableView) {
        try (BufferedReader reader = new BufferedReader(new FileReader(filePath));
             BufferedWriter writer = new BufferedWriter(new FileWriter(filePath + ".tmp"))) {
            String line;
            boolean isColumnSection = false;
            String currentId = "";
            while ((line = reader.readLine()) != null) {
                line = line.trim();
                if (line.startsWith("[") && line.endsWith("]")) {
                    if (isColumnSection) {
                        writeColumnConfig(writer, currentId, dataTableView);
                    }
                    writer.write(line + "\n");
                    isColumnSection = line.contains("Title");
                    if (isColumnSection) {
                        currentId = line.substring(1, line.length() - 1); // Extract ID
                    }
                } else if (!isColumnSection) {
                    writer.write(line + "\n");
                }
            }
            // Handle last section if necessary
            if (isColumnSection) {
                writeColumnConfig(writer, currentId, dataTableView);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

        // Replace old file with new file
        File originalFile = new File(filePath);
        File tmpFile = new File(filePath + ".tmp");
        if (originalFile.delete()) {
            tmpFile.renameTo(originalFile);
        }
    }

    private static void writeColumnConfig(BufferedWriter writer, String columnId, TableView<RowData> dataTableView) throws IOException {
        for (TableColumn<RowData, ?> column : dataTableView.getColumns()) {
            if (column.getId() != null && column.getId().equals(columnId)) {
                writer.write("title=" + column.getText() + "\n");
                writer.write("width=" + (int) column.getWidth() + "\n");
                break;
            }
        }
    }

    public static List<String> getColumnsIds() {
        return columnsIds;
    }

    public static void setColumnsIds(List<String> columnsIds) {
        TableUtil.columnsIds = columnsIds;
    }

    public static List<String> getColumnsNames() {
        return columnsNames;
    }

    public static void setColumnsNames(List<String> columnsNames) {
        TableUtil.columnsNames = columnsNames;
    }

    public static void generateTableColumns(TableView<RowData> dataTableView) {

        columnsNames = new ArrayList<>();
        columnsIds = new ArrayList<>();
        ObservableList<TableColumn<RowData, ?>> columns = dataTableView.getColumns();
        LinkedHashMap<String, Object[]> map = getTableColumnsConfig();
        List<String> names = new ArrayList<String>();
        for (TableColumn<RowData, ?> column : columns) {
            names.add(column.getId());
        }
        dataTableView.getColumns().clear();
        for (String id : names) {
            Object[] configs = map.get(id);

            if (configs != null && id.equals("Title17")) {
                // ��ӡ���⴦��
                TableColumn<RowData, Boolean> checkBoxColumn = new TableColumn<>("" + configs[0]);
                checkBoxColumn.setPrefWidth((int) configs[1]);
                checkBoxColumn.setCellValueFactory(cellData -> cellData.getValue().checkBoxValueProperty());
                checkBoxColumn.setCellFactory(cellData -> new CheckBoxTableCell<>());
                dataTableView.getColumns().add(checkBoxColumn);
                checkBoxColumn.setId(id);
            } else if (configs != null) {
//				if ((int) configs[1] == 0)
//					continue;
                System.out.println("\"\"+configs[0]:" + "" + configs[0]);
                columnsNames.add("" + configs[0]);
                columnsIds.add(id);
                TableColumn<RowData, String> newColumn = new TableColumn<>("" + configs[0]);
                newColumn.setId(id);
                newColumn.setMinWidth(0);
                newColumn.setPrefWidth((int) configs[1]);
                dataTableView.getColumns().add(newColumn);
                newColumn.setCellValueFactory(
                        new Callback<CellDataFeatures<RowData, String>, ObservableValue<String>>() {
                            @Override
                            public ObservableValue<String> call(CellDataFeatures<RowData, String> param) {
                                return param.getValue().getCellValue(newColumn.getId());
                            }
                        });
                newColumn.setCellFactory(col -> new CustomTextFieldTableCell<>(new DefaultStringConverter()));
                newColumn.setOnEditCommit(event -> {
                    RowData rowData = event.getRowValue();
                    rowData.setCellValue(newColumn.getId(), new SimpleStringProperty(event.getNewValue()));
                });

            }

        }


        columnsNames.remove("打印");
        columnsIds.remove("Title0");
    }


}